package com.centaline.androidsalesblog.base;

import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.view.View;

import com.android.volley.VolleyError;
import com.centaline.androidsalesblog.R;
import com.centaline.androidsalesblog.api.usercenter.CollectInfoListApi;
import com.centaline.androidsalesblog.events.MineInfoUpdate;
import com.centaline.androidsalesblog.model.businissobject.CollectInfoBo;
import com.centaline.androidsalesblog.model.responseobject.CollectInfoListRo;
import com.centaline.androidsalesblog.model.responseobject.SimpleUserCenterRo;
import com.centaline.androidsalesblog.rx.request.RxRequest;
import com.centaline.androidsalesblog.widgets.MRecyclerView;
import com.centanet.framework.interfaces.IRecycleViewListener;
import com.centanet.framework.interfaces.IResponseListener;
import com.trello.rxlifecycle.FragmentEvent;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;

import rx.functions.Action1;

/**
 * 收藏基类
 * Created by guilin on 16/3/22.
 */
public abstract class BaseCollectFragment<T> extends BaseFragment {

    protected MRecyclerView mRecyclerView;

    protected ArrayList<CollectInfoBo> collectList = new ArrayList<>();
    protected CollectInfoListApi collectInfoListApi;
    protected int iRefreshType = 1;
    protected boolean hasRequest;//是否请求过
    protected ArrayList<T> list = new ArrayList<>();

    @Override
    protected int setLayoutId() {
        return R.layout.layout_m_recyclerview;
    }

    @Override
    protected void findViews(View view) {
        mRecyclerView = (MRecyclerView) view.findViewById(R.id.mRecyclerView);
    }

    @Override
    protected void initView() {
        mRecyclerView.setIRecycleViewListener(new IRecycleViewListener() {
            @Override
            public void downRefresh() {
                hasRequest = true;
                iRefreshType = 1;
                collectInfoListApi.setFirstIndex(1);
                request();
            }

            @Override
            public void upRefresh() {
                iRefreshType = 2;
                collectInfoListApi.setFirstIndex(collectList.size() / 10 + 1);
                request();
            }

            @Override
            public void onItemClick(int position) {
                ItemClick(list.get(position));
            }
        });
        mRecyclerView.setDefaultText("没有收藏记录");
        mRecyclerView.setAdapter(initAdapter());
        ItemTouchHelper.Callback callback = new ItemTouchHelper.Callback() {
            @Override
            public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
                return makeMovementFlags(ItemTouchHelper.ACTION_STATE_IDLE, ItemTouchHelper.START);
            }

            @Override
            public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
                return false;
            }

            @Override
            public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
                final int position = viewHolder.getAdapterPosition();
                RxRequest.cancelCollect(BaseCollectFragment.class, String.valueOf(collectList.get(position).getCollectID()))
                        .compose(BaseCollectFragment.this.<SimpleUserCenterRo>bindUntilEvent(FragmentEvent.DESTROY))
                        .subscribe(new Action1<SimpleUserCenterRo>() {
                            @Override
                            public void call(SimpleUserCenterRo simpleUserCenterRo) {
                                if (0 == simpleUserCenterRo.getResultNo()) {
                                    collectList.remove(position);
                                    list.remove(position);
                                    mRecyclerView.notifyItemRemoved(position);
                                    EventBus.getDefault().post(new MineInfoUpdate(1));
                                } else {
                                    mRecyclerView.notifyItemChanged(position);
                                }
                            }
                        }, new Action1<Throwable>() {
                            @Override
                            public void call(Throwable throwable) {
                                mRecyclerView.notifyItemChanged(position);
                            }
                        });
            }

            @Override
            public void clearView(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
                super.clearView(recyclerView, viewHolder);
            }

            @Override
            public void onSelectedChanged(RecyclerView.ViewHolder viewHolder, int actionState) {
                super.onSelectedChanged(viewHolder, actionState);
            }
        };
        ItemTouchHelper itemTouchHelper = new ItemTouchHelper(callback);
        itemTouchHelper.attachToRecyclerView(mRecyclerView.getRecyclerView());

        collectInfoListApi = new CollectInfoListApi(BaseCollectFragment.class, CollectInfoListRo.class,
                new IResponseListener<CollectInfoListRo>() {
                    @Override
                    public void onResponse(CollectInfoListRo collectInfoListRo) {
                        ArrayList<CollectInfoBo> temp = collectInfoListRo.getList();
                        if (iRefreshType == 1) {
                            collectList.clear();
                            list.clear();
                        }
                        if (temp == null || temp.size() == 0) {
                            mRecyclerView.stopRefresh(false);
                            if (iRefreshType == 1) {
                                snack(collectInfoListRo.getMessage());
                            }
                        } else {
                            collectList.addAll(temp);
                            StringBuilder ids = new StringBuilder();
                            for (CollectInfoBo collectInfoBo : temp) {
                                ids.append(collectInfoBo.getCollectValue()).append(",");
                            }
                            ids.deleteCharAt(ids.length() - 1);
                            requestList(ids.toString());
                        }
                    }

                    @Override
                    public void onErrorResponse(VolleyError error) {
                        mRecyclerView.refreshError();
                    }
                });
        initApi(collectInfoListApi);
        initOtherApi();
    }

    @Override
    protected void loadData() {
        if (!hasRequest) {
            mRecyclerView.startRefresh();
        } else {
            mRecyclerView.refreshStatus();
        }
    }

    /**
     * 初始化api
     */
    protected abstract void initApi(CollectInfoListApi collectInfoListApi);

    /**
     * 初始化其他api
     */
    protected abstract void initOtherApi();

    /**
     * 请求列表id数据
     */
    protected void request() {
        collectInfoListApi.startRequest();
    }

    /**
     * 请求列表数据
     */
    protected abstract void requestList(String ids);

    /**
     * 初始化Adapter
     */
    protected abstract RecyclerView.Adapter initAdapter();

    /**
     * item 点击事件
     */
    protected abstract void ItemClick(T t);

    /**
     * 停止刷新
     */
    protected void stopRefresh(ArrayList<T> temp) {
        if (iRefreshType == 1) {
            list.clear();
        }
        if (temp == null) {
            mRecyclerView.stopRefresh(false);
        } else {
            list.addAll(temp);
            mRecyclerView.stopRefresh(temp.size() == 10);
        }
    }
}
